// axios 二次封装
// 导入axios
import axios, { type AxiosRequestConfig, AxiosResponse } from 'axios';

const instance = axios.create({
    // 设置请求的基础地址
    baseURL: 'http://localhost:3000/api',
    // 设置请求头
    headers: {
        'Content-Type': 'application/json',
        // 'Authorization': 'Bearer ' + token,
    },
    // 设置超时
    timeout: 1000,
});

instance.interceptors.request.use((config: AxiosRequestConfig | any) => config);
instance.interceptors.response.use((res: AxiosResponse | any) => {
    const obj = JSON.parse(res.data);
    const resp:ResponseData = obj as ResponseData;
    console.log(obj);
    console.log(resp);
    return res.data;
}, (err: any) => {
    const resp:ResponseData = {
        success: false,
        code: err.code,
        message: err.message || '请求失败'
    }

    return Promise.reject(resp);
});

// 定义一个接口，用于定义您的响应参数
interface ResponseData {
    success: boolean;
    code: string;
    message?: string;
    data?: any;
}

interface IHttp {
    get<T>(url: string, data?: any): Promise<T>;
    post<T>(url: string, data?: any): Promise<T>;
}

const http: IHttp = {
    get(url, data) {
        return instance.get(url, data);
    },
    post(url, data) {
        return instance.post(url, data);
    },

}

export default http;